package com.faithbj.printer.service.Impl;

import com.faithbj.printer.service.FilePrinter;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class FilePrinterImpl implements FilePrinter {

	@Override
	public void printWord(String filePath) {
		 ComThread.InitSTA();
	        ActiveXComponent wd = new ActiveXComponent("Word.Application");
	        //设置默认打印机
//	        wd.setProperty("ActivePrinter", new Variant("HP LaserJet 4 local on LPT1:"));
	        try {
	            //設置是否打开文档
//	            Dispatch.put(wd, "Visible", new Variant(false));
	        	wd.setProperty("Visible", new Variant(false));
	            Dispatch document = wd.getProperty("Documents").toDispatch();
	            Dispatch doc = Dispatch.invoke(document, "Open", Dispatch.Method,
	                    new Object[] { filePath, new Variant(false)}, new int[1]).toDispatch();
	            // 开始打印
	            Dispatch.callN(doc, "PrintOut", new Object[]{});//打印可设置的参数参见：http://msdn.microsoft.com/zh-cn/library/microsoft.office.tools.word.document.printout%28VS.80%29.aspx
	            wd.invoke("Quit", new Variant[] {});
	        } catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	            // 始终释放资源
	            ComThread.Release();
	        }

	}

	@Override
	public void printExcel(String filePath) {
        ComThread.InitSTA();
        ActiveXComponent xl = new ActiveXComponent("ET.Application");
        try {
            Dispatch.put(xl, "Visible", new Variant(true));
            Dispatch workbooks = xl.getProperty("Workbooks").toDispatch();
            // 打开文档
            Dispatch excel = Dispatch.call(workbooks, "Open", filePath)
                    .toDispatch();
            // 开始打印
            Dispatch.call(excel, "PrintOut");
            xl.invoke("Quit", new Variant[] {});
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 始终释放资源
            ComThread.Release();
        }
    }

}
